package handlers

import (
	"data_service/server"
	"fmt"
	"net/http"
	"strconv"

	"data_service/utils"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

var friendService *server.FriendService

// InitFriendService 初始化好友服务
func InitFriendService(db *gorm.DB) {
	friendService = server.NewFriendService(db)
}

// AddFriendHandler 添加好友
func AddFriendHandler(c *gin.Context) {
	fmt.Printf("[ADD_FRIEND] 收到添加好友请求 - IP: %s\n", c.ClientIP())

	var req struct {
		UserID   uint `json:"user_id" binding:"required"`
		FriendID uint `json:"friend_id" binding:"required"`
	}

	if err := utils.BindJSON(c, &req); err != nil {
		fmt.Printf("[ADD_FRIEND] JSON解析失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_JSON_FORMAT",
			"message": "请求参数格式错误",
			"data":    gin.H{"details": "请检查JSON格式是否正确"},
		})
		return
	}

	fmt.Printf("[ADD_FRIEND] 解析成功 - 用户ID: %d, 好友ID: %d\n", req.UserID, req.FriendID)

	if err := friendService.AddFriend(req.UserID, req.FriendID); err != nil {
		fmt.Printf("[ADD_FRIEND] 添加好友失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "ADD_FRIEND_FAILED",
			"message": "添加好友失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[ADD_FRIEND] 添加好友成功 - 用户ID: %d, 好友ID: %d\n", req.UserID, req.FriendID)
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "添加好友成功",
		"data":    gin.H{"user_id": req.UserID, "friend_id": req.FriendID},
	})
}

// GetFriendsHandler 获取好友列表
func GetFriendsHandler(c *gin.Context) {
	userIDStr := c.Query("user_id")
	if userIDStr == "" {
		fmt.Printf("[GET_FRIENDS] 用户ID参数缺失\n")
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "MISSING_USER_ID",
			"message": "用户ID不能为空",
			"data":    gin.H{"details": "请提供用户ID参数"},
		})
		return
	}

	userID, err := strconv.ParseUint(userIDStr, 10, 32)
	if err != nil {
		fmt.Printf("[GET_FRIENDS] 用户ID格式错误: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_USER_ID",
			"message": "用户ID格式错误",
			"data":    gin.H{"details": "用户ID必须是数字"},
		})
		return
	}

	fmt.Printf("[GET_FRIENDS] 收到获取好友列表请求 - 用户ID: %d\n", userID)

	friends, err := friendService.GetFriends(uint(userID))
	if err != nil {
		fmt.Printf("[GET_FRIENDS] 获取好友列表失败: %v\n", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    "GET_FRIENDS_FAILED",
			"message": "获取好友列表失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[GET_FRIENDS] 获取好友列表成功 - 用户ID: %d, 好友数量: %d\n", userID, len(friends))
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "获取好友列表成功",
		"data":    friends,
	})
}

// DeleteFriendHandler 删除好友
func DeleteFriendHandler(c *gin.Context) {
	fmt.Printf("[DELETE_FRIEND] 收到删除好友请求 - IP: %s\n", c.ClientIP())

	var req struct {
		UserID   uint `json:"user_id" binding:"required"`
		FriendID uint `json:"friend_id" binding:"required"`
	}

	if err := utils.BindJSON(c, &req); err != nil {
		fmt.Printf("[DELETE_FRIEND] JSON解析失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_JSON_FORMAT",
			"message": "请求参数格式错误",
			"data":    gin.H{"details": "请检查JSON格式是否正确"},
		})
		return
	}

	fmt.Printf("[DELETE_FRIEND] 解析成功 - 用户ID: %d, 好友ID: %d\n", req.UserID, req.FriendID)

	if err := friendService.DeleteFriend(req.UserID, req.FriendID); err != nil {
		fmt.Printf("[DELETE_FRIEND] 删除好友失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "DELETE_FRIEND_FAILED",
			"message": "删除好友失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[DELETE_FRIEND] 删除好友成功 - 用户ID: %d, 好友ID: %d\n", req.UserID, req.FriendID)
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "删除好友成功",
		"data":    gin.H{"user_id": req.UserID, "friend_id": req.FriendID},
	})
}

// SendFriendRequestHandler 发送好友请求
func SendFriendRequestHandler(c *gin.Context) {
	fmt.Printf("[SEND_FRIEND_REQUEST] 收到发送好友请求 - IP: %s\n", c.ClientIP())

	var req struct {
		FromUserID uint   `json:"from_user_id" binding:"required"`
		ToUserID   uint   `json:"to_user_id" binding:"required"`
		Message    string `json:"message"`
	}

	if err := utils.BindJSON(c, &req); err != nil {
		fmt.Printf("[SEND_FRIEND_REQUEST] JSON解析失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_JSON_FORMAT",
			"message": "请求参数格式错误",
			"data":    gin.H{"details": "请检查JSON格式是否正确"},
		})
		return
	}

	// 设置默认消息
	if req.Message == "" {
		req.Message = "我想加你为好友"
	}

	fmt.Printf("[SEND_FRIEND_REQUEST] 解析成功 - 发送者ID: %d, 接收者ID: %d, 消息: %s\n",
		req.FromUserID, req.ToUserID, req.Message)

	if err := friendService.SendFriendRequest(req.FromUserID, req.ToUserID, req.Message); err != nil {
		fmt.Printf("[SEND_FRIEND_REQUEST] 发送好友请求失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "SEND_REQUEST_FAILED",
			"message": "发送好友请求失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[SEND_FRIEND_REQUEST] 发送好友请求成功 - 发送者ID: %d, 接收者ID: %d\n",
		req.FromUserID, req.ToUserID)
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "发送好友请求成功",
		"data":    gin.H{"from_user_id": req.FromUserID, "to_user_id": req.ToUserID},
	})
}

// GetFriendRequestsHandler 获取好友请求列表
func GetFriendRequestsHandler(c *gin.Context) {
	userIDStr := c.Query("user_id")
	requestType := c.Query("type") // received 或 sent

	if userIDStr == "" {
		fmt.Printf("[GET_FRIEND_REQUESTS] 用户ID参数缺失\n")
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "MISSING_USER_ID",
			"message": "用户ID不能为空",
			"data":    gin.H{"details": "请提供用户ID参数"},
		})
		return
	}

	if requestType == "" {
		requestType = "received" // 默认获取收到的请求
	}

	userID, err := strconv.ParseUint(userIDStr, 10, 32)
	if err != nil {
		fmt.Printf("[GET_FRIEND_REQUESTS] 用户ID格式错误: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_USER_ID",
			"message": "用户ID格式错误",
			"data":    gin.H{"details": "用户ID必须是数字"},
		})
		return
	}

	fmt.Printf("[GET_FRIEND_REQUESTS] 收到获取好友请求列表请求 - 用户ID: %d, 类型: %s\n", userID, requestType)

	requests, err := friendService.GetFriendRequests(uint(userID), requestType)
	if err != nil {
		fmt.Printf("[GET_FRIEND_REQUESTS] 获取好友请求列表失败: %v\n", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    "GET_REQUESTS_FAILED",
			"message": "获取好友请求列表失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[GET_FRIEND_REQUESTS] 获取好友请求列表成功 - 用户ID: %d, 请求数量: %d\n", userID, len(requests))
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "获取好友请求列表成功",
		"data":    requests,
	})
}

// RespondToFriendRequestHandler 处理好友请求
func RespondToFriendRequestHandler(c *gin.Context) {
	requestIDStr := c.Param("id")
	if requestIDStr == "" {
		fmt.Printf("[RESPOND_FRIEND_REQUEST] 请求ID参数缺失\n")
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "MISSING_REQUEST_ID",
			"message": "请求ID不能为空",
			"data":    gin.H{"details": "请提供请求ID参数"},
		})
		return
	}

	requestID, err := strconv.ParseUint(requestIDStr, 10, 32)
	if err != nil {
		fmt.Printf("[RESPOND_FRIEND_REQUEST] 请求ID格式错误: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_REQUEST_ID",
			"message": "请求ID格式错误",
			"data":    gin.H{"details": "请求ID必须是数字"},
		})
		return
	}

	var req struct {
		UserID uint   `json:"user_id" binding:"required"`
		Action string `json:"action" binding:"required"` // accept 或 reject
	}

	if err := utils.BindJSON(c, &req); err != nil {
		fmt.Printf("[RESPOND_FRIEND_REQUEST] JSON解析失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_JSON_FORMAT",
			"message": "请求参数格式错误",
			"data":    gin.H{"details": "请检查JSON格式是否正确"},
		})
		return
	}

	fmt.Printf("[RESPOND_FRIEND_REQUEST] 解析成功 - 请求ID: %d, 用户ID: %d, 操作: %s\n",
		requestID, req.UserID, req.Action)

	if err := friendService.RespondToFriendRequest(uint(requestID), req.UserID, req.Action); err != nil {
		fmt.Printf("[RESPOND_FRIEND_REQUEST] 处理好友请求失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "RESPOND_REQUEST_FAILED",
			"message": "处理好友请求失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[RESPOND_FRIEND_REQUEST] 处理好友请求成功 - 请求ID: %d, 用户ID: %d, 操作: %s\n",
		requestID, req.UserID, req.Action)
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "处理好友请求成功",
		"data":    gin.H{"request_id": requestID, "action": req.Action},
	})
}

// CancelFriendRequestHandler 取消好友请求
func CancelFriendRequestHandler(c *gin.Context) {
	requestIDStr := c.Param("id")
	if requestIDStr == "" {
		fmt.Printf("[CANCEL_FRIEND_REQUEST] 请求ID参数缺失\n")
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "MISSING_REQUEST_ID",
			"message": "请求ID不能为空",
			"data":    gin.H{"details": "请提供请求ID参数"},
		})
		return
	}

	requestID, err := strconv.ParseUint(requestIDStr, 10, 32)
	if err != nil {
		fmt.Printf("[CANCEL_FRIEND_REQUEST] 请求ID格式错误: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_REQUEST_ID",
			"message": "请求ID格式错误",
			"data":    gin.H{"details": "请求ID必须是数字"},
		})
		return
	}

	var req struct {
		UserID uint `json:"user_id" binding:"required"`
	}

	if err := utils.BindJSON(c, &req); err != nil {
		fmt.Printf("[CANCEL_FRIEND_REQUEST] JSON解析失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "INVALID_JSON_FORMAT",
			"message": "请求参数格式错误",
			"data":    gin.H{"details": "请检查JSON格式是否正确"},
		})
		return
	}

	fmt.Printf("[CANCEL_FRIEND_REQUEST] 解析成功 - 请求ID: %d, 用户ID: %d\n", requestID, req.UserID)

	if err := friendService.CancelFriendRequest(uint(requestID), req.UserID); err != nil {
		fmt.Printf("[CANCEL_FRIEND_REQUEST] 取消好友请求失败: %v\n", err)
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "CANCEL_REQUEST_FAILED",
			"message": "取消好友请求失败",
			"data":    gin.H{"details": err.Error()},
		})
		return
	}

	fmt.Printf("[CANCEL_FRIEND_REQUEST] 取消好友请求成功 - 请求ID: %d, 用户ID: %d\n", requestID, req.UserID)
	c.JSON(http.StatusOK, gin.H{
		"code":    "SUCCESS",
		"message": "取消好友请求成功",
		"data":    gin.H{"request_id": requestID},
	})
}
